package com.laivi.basic.model.file.writer;

import java.io.File;
import java.io.IOException;

import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

import com.laivi.basic.module.log.Log;
import com.laivi.basic.module.log.Logs;

/**
 * @author laivi.zhu@gmail.com
 * @date 2014-7-10
 * description:
 */
public class XlsWriter implements IExcelWriter {
	private final static Log log=Logs.getLog(XlsWriter.class);
	private WritableWorkbook book;
	private WritableSheet sheet;
	
	public XlsWriter(String path){
		this(new File(path));
	}
	
	public XlsWriter(File file){
		try {
			if(file.exists()){
				book=Workbook.createWorkbook(file,Workbook.getWorkbook(file));
			}else{
				book=Workbook.createWorkbook(file);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (BiffException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void setSheet(int index) {
		Sheet[] sheets=book.getSheets();
		index=index<0?0:index;
		if(sheets.length<=index){
			for(int i=sheets.length;i<=index;i++){
				book.createSheet("sheet"+(i+1), i);
			}
		}
		sheet=book.getSheet(index);
	}

	@Override
	public void writeCell(int row, int col, String content) {
		Label label=new Label(col,row,content);
		try {
			sheet.addCell(label);
		} catch (WriteException e) {
			log.error(e.getMessage(), e);
		}
	}
	
	@Override
	public void writeCell(int row, char col, String content) {
		int colNum=Character.toUpperCase(col)-65;
		writeCell(row,colNum,content);
	}

	@Override
	public void close() {
		try {
			if(book!=null){
				book.write();
				book.close();
			}
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		} catch (WriteException e) {
			log.error(e.getMessage(), e);
		}
	}
}
